package com.tju.backend.service.business.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.backend.dao.ware.OrderMapper;
import com.tju.backend.dao.ware.OutWarehouseLogMapper;
import com.tju.backend.dao.ware.StereoscopicWarehouseMapper;
import com.tju.backend.dao.ware.WarehousingMapper;
import com.tju.backend.entity.OutWarehouseLog;
import com.tju.backend.entity.SysUser;
import com.tju.backend.entity.TStereoscopicWarehouse;
import com.tju.backend.entity.TWarehousing;
import com.tju.backend.plugin.common.GlobalCall;
import com.tju.backend.plugin.common.Push;
import com.tju.backend.plugin.web_socket.TioMsgHandler;
import com.tju.backend.service.business.IStereoscopicWarehouseService;
import com.tju.backend.service.common.ServiceException;
import com.tju.backend.utils.hex.HexStringUtil;
import com.tju.backend.utils.result.Result;
import com.tju.backend.utils.result.ResultEnum;
import com.tju.backend.utils.result.ResultUtil;
import com.tju.backend.utils.tool.ChineseExceptionUtils;
import com.tju.backend.utils.tool.ClientParameters;
import com.tju.backend.utils.tool.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.tju.backend.plugin.common.GlobalCall.redisService;
import static com.tju.backend.plugin.common.GlobalCall.str;

/**
 * 立体仓库实际库位Service业务层处理
 *
 * @author xt-exhibition
 * @date 2021-05-18
 */
@Slf4j
@Service
public class SwServiceImpl implements IStereoscopicWarehouseService {
    @Autowired
    private StereoscopicWarehouseMapper stereoscopicWarehouseMapper;
    @Autowired
    private OutWarehouseLogMapper outWarehouseLogMapper;
    @Autowired
    private ChineseExceptionUtils zhCh;

    /**
     * 出仓
     *
     * @param id
     */
    @Override
    @Transactional
    public Result<Object> outWarehouse(Integer id) {
        try {
            String pause = (String) redisService.get(Constants.Pause);
            if (pause == null) {
                redisService.redisSetData(Constants.Pause, Constants.STRING, 4);
                List<TStereoscopicWarehouse> list = stereoscopicWarehouseMapper.selectSwByNumber(id);
                JSONObject data = Optional.ofNullable(list)
                        .filter(l -> l.size() >= 1 && l.size() <= 2)
                        .map(l -> {
                            //修改立体库位状态
                            int rows = stereoscopicWarehouseMapper.updateStatusByBarcode(l.get(0).getBoxBarcode(),new Date());
                            TStereoscopicWarehouse sw = stereoscopicWarehouseMapper.selectOne(l.get(0).getBoxBarcode());
                            //todo: 进行PLC发送出货
                            Push.tcpPush(GlobalCall.str(sw));
                            //出仓
                            Push.push(ResultUtil.success(ResultEnum.OUTWAREHOUSE, GlobalCall.str(sw)));
                            //封装参数
                            return new OutWarehouseLog(l.get(0), rows);
                        })
                        .filter(s -> s.getBarcode() != null)
                        .map(s -> {
                            //插入出货日志
                            outWarehouseLogMapper.insertOutWarehouseLog(s);
                            //统计数据
                            int total = stereoscopicWarehouseMapper.getTotal();   //总数
                            int num = stereoscopicWarehouseMapper.getUsedNum(); //已用
                            int surplus = total - num; //剩余
                            return Constants.jsonObject(s, total, num, surplus);
                        })
                        .orElseThrow(() -> new ServiceException(zhCh.AbnormalOrder));
                return ResultUtil.success(ResultEnum.SUCCESS, data);
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, zhCh.HoldTheLinePlease);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }

    }

    /**
     * 查询出口日志
     *
     * @return
     */
    @Override
    public Result<Object> getOutWarehouseLog() {
        return ResultUtil.success(ResultEnum.SUCCESS, outWarehouseLogMapper.getOutWarehouseLog());
    }

    /**
     * 查询订单状态
     *
     * @return
     */
    @Override
    public Result<Object> getOrder(ClientParameters parameters) {
        try {
            IPage<TStereoscopicWarehouse> iPage = Optional.ofNullable(parameters)
                    .filter(p -> (p.getPage() != null && p.getLimit() != null))//过滤
                    .map(s -> {
                        Page<TStereoscopicWarehouse> page = new Page<>(s.getPage(), s.getLimit());
                        return stereoscopicWarehouseMapper.getOrderStatus(page, null);
                    })
                    .orElseThrow(() -> new ServiceException(zhCh.NoPagination));
            Result<Object> s = ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
            s.setCode(0);//根据layui数据表格的格式来
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }


}
